<!-- 折叠轮播图 组件-->
<template>
  <view>
    <view class="mb-1 flex items-center justify-between">
      <view class="text-40 c-#333 font-bold">我的学社</view>
      <view class="flex flex-col items-center">
        <view class="c-#333 text-24">{{ state.currentSwiperIndex }}<text class="c-#B5B5B5">/{{ maxSwiperNum }}</text>
        </view>
        <u-line-progress style="width: 80rpx; margin-top: -16rpx;" active-color="#F4AF22" inactive-color="#FFEBC3"
          :percent="progressPercent" :show-percent="false" height="4"></u-line-progress>
      </view>
    </view>
    <view class="swpbig">
      <view class="swiperPanel w-full h-700" ref="swiperPanel" @touchstart="startMove" @touchend="endMove">
        <view class="swiperItem" v-for="(item, index) in data" :key="index"
          :style="{ transform: state.itemStyle[index]?.transform, zIndex: state.itemStyle[index]?.zIndex, opacity: state.itemStyle[index]?.opacity }">
          <view class="children relative shadow-card rounded-md bg-white w-640 h-full py-3">
            <view class="px-4">
              <!-- 标签 已过期 优先级最高 全员可见 -->
              <view v-if="item.club.status == 4"
                class="absolute top-9 right-0 w-118 h-40 rounded-l-sm flex items-center justify-center bg-#FF513A">
                <view class="text-24 c-white ml-1">已过期</view>
              </view>
              <view v-else>
                <!-- 社长 / 非社长 -->
                <!-- 标签 非正常状态 -->
                <view v-if="item.club.status != 1 || item.audit_status != 1"
                  class="absolute top-9 right-0 w-118 h-40 rounded-l-sm flex items-center justify-center"
                  :class="[societyTag(item.member_position == 3 ? item.club.status : item.audit_status, 'type', item.member_position) === 'warming' ? 'bg-#F4AF22' : 'bg-#FF513A']">
                  <view class="text-24 c-white ml-1">{{ societyTag(item.member_position == 3 ? item.club.status :
                    item.audit_status, 'label', item.member_position) }}</view>
                </view>
                <!-- 标签 正常状态且为社长vip距过期30天 社长非顾问身份 -->
                <view
                  v-if="item.club.status == 1 && item.member_position == 3 && item.creator.identity != 1 && onValidityRange(item.creator.vip_validity)"
                  class="absolute top-9 right-0 w-118 h-40 rounded-l-sm flex items-center justify-center bg-#F4AF22">
                  <u-image width="28" height="28" src="/static/images/home/ic_clock.png"></u-image>
                  <view class="text-24 c-white ml-1">{{ onCountDown(item.creator.vip_validity) }}天</view>
                </view>
              </view>
              <view class="mb-1 c-#333 text-28 text-maxline-1"
                :class="[{ 'max-w-500': item.club.status != 1 || item.audit_status != 1 || item.club.status == 1 && item.member_position == 3 && item.creator.identity != 1 && onValidityRange(item.creator.vip_validity) }]">
                {{ item?.club?.club_name }}
              </view>
              <u-image border-radius="12" width="100%" height="416" :src="item?.club?.cover_image"
                @click="enterSociety('/package_society/pages/society/index?tabId=0', item.club_id, item)"></u-image>
              <view class="flex items-center mt-2">
                <view class="flex relative w-80 h-32">
                  <view v-for="(avatar, index) in item.avatar_info" :key="index"
                    class="rounded-full bg-#808080 border-avatar"
                    :style="{ 'position': 'absolute', 'left': (index * 16) + 'rpx', 'z-index': 10 - index }">
                    <u-image shape="circle" width="32" height="32"
                      :src="avatar?.user?.avatar ?? '/static/images/user/ic_def_avatar.png'"></u-image>
                  </view>
                </view>
                <view class="c-#B5B5B5 text-24 ml-2">创建人：{{ item?.creator?.nickname }}</view>
                <view class="w-2 h-22 mx-2" />
                <view class="c-#B5B5B5 text-24">成员：{{ item?.club?.member_number }}</view>
              </view>
              <view class="h-2 w-full bg-#E5E5E5 mt-3 mb-4" />
            </view>
            <view class="flex">
              <view class="w-20% flex flex-col items-center"
                v-for="(option, index) in formatOptions(item.member_position)" :key="index"
                @click="enterSociety(option.url, item.club_id, item)">
                <view class="relative">
                  <u-image mode="aspectFit" width="36" height="36" :src="option.icon"></u-image>

                  <u-badge v-if="option.id == 1 && option.notice && item.question_unread" :is-dot="true" :offset="[-8, -8]"
                    type="error"></u-badge>
                  <u-badge v-if="option.id == 2 && option.notice && item.service_unread" :is-dot="true" :offset="[-8, -8]"
                    type="error"></u-badge>
                  <u-badge v-if="option.id == 4 && option.notice && item.member_unread" :is-dot="true" :offset="[-8, -8]"
                    type="error"></u-badge>
                  <u-badge v-if="option.id == 5 && option.notice && item.dynamic_unread" :is-dot="true" :offset="[-8, -8]"
                    type="error"></u-badge>
                </view>
                <view class="c-#515151 text-24 mt-1">{{ option.title }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 通用提示弹窗 -->
    <u-modal v-model="state.modalConfig.showTipModal" :show-title="false" border-radius="12" :show-confirm-button="false">
      <view class="slot-content">
        <view class="flex justify-center c-#333 text-32 font-bold">温馨提示</view>
        <view @click="state.modalConfig.showTipModal = false"
          class="absolute top-0 right-17 w-166 h-166 flex justify-end">
          <image class="mt-3 mr-2 w-22 h-22" src="/static/images/home/ic_delete.png" />
        </view>

        <view class="text-center c-#333 text-sm my-10">
          {{ state.modalConfig.desc }}
        </view>
        <view class="flex items-center justify-center">
          <view v-if="state.modalConfig.showCloseBtn" class="btn-save mx-3"
            @click="state.modalConfig.showTipModal = false">知道了</view>
          <view v-if="state.modalConfig.showCancelBtn" class="btn-save mx-3"
            @click="onCancelApply(state.modalConfig.clubId)">取消申请</view>
          <view v-if="state.modalConfig.showJumpBtn" class="btn-save mx-3"
            @click="onTipModalConfrim(state.modalConfig.jumpUrl)">{{ state.modalConfig.btnName }}
          </view>
          <view v-if="state.modalConfig.showEnterBtn" class="btn-save mx-3" @click="onEnter(state.modalConfig.enterUrl)">
            知道了
          </view>
        </view>
      </view>
    </u-modal>
  </view>
</template>

<script setup>
import { navigate, showToast } from "@/common/util/uni";
import { actionList, societyCreaterStatus, societyMemberStatus } from '@/common/constant/society.js'
import { postSocietyCancelApply } from '@/common/http/module/society.js'
import dayjs from 'dayjs'

const emit = defineEmits(['refresh'])
const props = defineProps({
  data: {
    type: Array,
    default: () => []
  }
})

const state = reactive({
  currentSwiperIndex: 1,
  vipValidity: '', // 30天倒计时
  slideNote: {
    x: 0,
    y: 0
  },
  screenWidth: 0,
  itemStyle: [],
  modalConfig: {
    desc: '', // 提示内容
    showTipModal: false, // 提示弹窗
    showCloseBtn: false,
    showJumpBtn: false,
    btnName: '', // 按钮名称,
    jumpUrl: '',
    showEnterBtn: false,
    enterUrl: '',
    showCancelBtn: false, // 取消申请学社按钮
    clubId: '' // 学社id
  },
})

watch(() => props.data, (val) => {
  if (val) {
    state.itemStyle = []
    state.currentSwiperIndex = 1
    // 计算swiper样式
    val.forEach((item, index) => {
      state.itemStyle.push(getStyle(index))
    })
  }
})

// 轮播图进度相关
const maxSwiperNum = computed(() => props.data.length)
const progressPercent = computed(() => (state.currentSwiperIndex / maxSwiperNum.value) * 100)

function getStyle(e) {
  if (e == 0) {
    return {
      transform: 'scale(1) translate(0rpx,0rpx)',
      zIndex: 100,
      opacity: 1
    }
  } else {
    return {
      transform: 'scale(0.9) translate(84rpx,0rpx)',
      zIndex: 100 - e,
      opacity: 0.5 / e
    }
  }
}
function startMove(e) {
  state.slideNote.x = e.changedTouches[0] ? e.changedTouches[0].pageX : 0;
  state.slideNote.y = e.changedTouches[0] ? e.changedTouches[0].pageY : 0;
}

function endMove(e) {
  let newList = JSON.parse(JSON.stringify(state.itemStyle));
  if ((e.changedTouches[0].pageX - state.slideNote.x) < -30) {
    // 向左滑动
    let last = [newList.pop()]
    newList = last.concat(newList)
    state.currentSwiperIndex < props.data.length ? state.currentSwiperIndex++ : state.currentSwiperIndex = 1
  }
  if ((e.changedTouches[0].pageX - state.slideNote.x) > 30) {
    // 向右滑动
    newList.push(newList[0])
    newList.splice(0, 1)
    state.currentSwiperIndex > 1 ? state.currentSwiperIndex-- : state.currentSwiperIndex = props.data.length

  }
  state.itemStyle = newList
}

// 获取学社身份对应的操作栏
function formatOptions(member_position) {
  return actionList.filter(v => member_position >= v.auth)
}

// 获取学社标签
function societyTag(status, type, member_position) {
  const statusList = member_position == 3 ? societyCreaterStatus : societyMemberStatus
  return statusList.find(v => v.value == status)?.[type] ?? ''
}

// 社长vip剩余30天范围内
function onValidityRange(vip_validity) {
  // 获取距过期结束30天前时间
  const warmDate = dayjs(vip_validity).subtract(30, 'day')
  // 当前时间是否在剩余30天范围内
  const isValidityRange = dayjs().isAfter(warmDate)
  return isValidityRange
}

// 社长会员过期倒计时
function onCountDown(vip_validity) {
  // 获取过期时间和当前时间的差异
  const endTime = dayjs(vip_validity)
  const nowTime = dayjs(new Date())
  const days = endTime.diff(nowTime, 'day') + 1
  return days
}

// 进入学社
function enterSociety(url, club_id, item) {
  // 学社状态:0=审核中,1=正常,2=禁用,3=已驳回,4=已过期
  const clubStatus = item.club.status
  // 申请加入学社审核状态:0=申请中,1=已通过,2=已驳回
  const auditStatus = item.audit_status
  // 是否是社长 学社身份:0=成员,1=顾问,2=管理员,3=社长
  const isCreator = item.member_position == 3
  // 社长快过期弹窗
  const isCreatorExpire = isCreator && onValidityRange(item.creator.vip_validity)
  // 距离过期时间
  const validityTime = onCountDown(item.creator.vip_validity)
  // 是否能进入学社
  const canEnterSociety = clubStatus == 1 && auditStatus == 1
  if (canEnterSociety) {
    if (isCreatorExpire && item.creator.identity != 1) {
      state.modalConfig = {
        showTipModal: true,
        desc: `您的【${item.club?.club_name}】会员权益还有${validityTime}天到期，过期后，将暂停使用学社权限，为了保证学社的正常使用，记得及时续费哦~`,
        showJumpBtn: true,
        btnName: '去续费',
        jumpUrl: '/package_user/pages/vip/add',
        showEnterBtn: true,
        enterUrl: `${url}&club_id=${club_id}`
      }
      return
    }
    navigate(`${url}&club_id=${club_id}`, true)
  } else {
    // 过期弹窗提醒
    if (clubStatus == 4) {
      const desc = isCreator ? '您的会员权益已经过期了，如若继续享用学社服务，要及时续费哦' : '此学社使用权益已过期，因此将暂停服务，具体情况可与社长联系'
      state.modalConfig = {
        showTipModal: true,
        desc,
        showCloseBtn: !isCreator,
        showJumpBtn: isCreator,
        btnName: '去续费',
        jumpUrl: '/package_user/pages/vip/add'
      }
    }
    // 审核弹窗提醒
    if (clubStatus == 0 || auditStatus == 0) {
      const desc = isCreator ? '您的创建学社申请还在审核中，审核结果会第一时间通过公众号以提醒的形式通知您~' : '您的加入学社申请还在审核中，审核结果会第一时间通过公众号以提醒的形式通知您~'
      state.modalConfig = {
        showTipModal: true,
        desc,
        showCloseBtn: true,
      }
    }
    // 驳回弹窗提醒
    if (clubStatus == 3 || auditStatus == 2) {
      const desc = isCreator ? '很抱歉，您的创建申请被驳回，请重新提交申请~' : '很抱歉，您的加入申请被驳回，请重新提交申请~'
      state.modalConfig = {
        showTipModal: true,
        desc,
        showCloseBtn: isCreator,
        showJumpBtn: true,
        btnName: isCreator ? '重新提交' : '去提交',
        jumpUrl: isCreator ? `/package_society/pages/society/add?club_id=${club_id}` : `/package_society/pages/society/detail?id=${item.club?.id}`,
        showCancelBtn: !isCreator,
        clubId: club_id
      }
    }
  }
}

function onEnter(url) {
  state.modalConfig.showTipModal = false
  navigate(url, true)
}

// 通用弹窗按钮事件
function onTipModalConfrim(jumpUrl) {
  navigate(jumpUrl)
  state.modalConfig.showTipModal = false
}

// 取消申请学社
function onCancelApply(club_id) {
  postSocietyCancelApply({ club_id }).then(() => {
    showToast('取消申请成功', 'none')
    state.modalConfig.showTipModal = false
    // 刷新列表
    emit('refresh')
  })
}

onMounted(() => {
  let macInfo = uni.getSystemInfoSync();
  state.screenWidth = macInfo.screenWidth;
  // 计算swiper样式
  state.itemStyle = []
  state.currentSwiperIndex = 1
  props.data.forEach((item, index) => {
    state.itemStyle.push(getStyle(index))
  })
})
</script>
<style lang="scss" scoped>
.slot-content {
  position: relative;
  padding: 24rpx 40rpx 40rpx;
}

.btn-save {
  width: 100%;
  height: 68rpx;
  line-height: 68rpx;
  text-align: center;
  color: #fff;
  font-size: 28rpx;
  border-radius: 10rpx;
  background-color: #F4AF22;
}

.border-avatar {
  border: 2rpx solid #fff;
}

.shadow-card {
  box-shadow: -1.2246468525851679e-16px 2px 6px 0px rgba(206, 143, 12, 0.1);
}

.swpbig {
  overflow: hidden;
}

.swiperPanel {
  overflow: hidden;
  position: relative;
  transition: all 0.2s;

  .swiperItem {
    width: 100%;
    height: calc(100% - 6rpx);
    position: absolute;
    top: 0;
    left: 0;
    transition: all .5s;
    margin-bottom: 6rpx;

    .children {
      position: relative;
      box-shadow: -4rpx 4rpx 12rpx 0px rgba(206, 143, 12, 0.1);
    }
  }
}
</style>